﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;

namespace Dapper.Library
{
    /// <summary>
    /// 反射扩展
    /// </summary>
    public static class ReflectExtension
    {
        /// <summary>
        /// 获取对象所有属性
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static PropertyInfo[] GetProperties(this object obj)
        {
            return obj.GetType().GetProperties().Where(f => !Attribute.IsDefined(f, typeof(DatabaseGeneratedAttribute))).ToArray();
        }

        /// <summary>
        /// 获取属性Key
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static PropertyInfo GetKeyPropertity(this object obj)
        {
            var properties = obj.GetType().GetProperties().Where(a => a.GetCustomAttribute<Tool.Model.DBFieldInfo>().IsPrimarykey).ToArray();

            if (!properties.Any())
                throw new Exception($"{nameof(obj)} 实体没有KeyAttribute Propertity");

            if (properties.Length > 1)
                throw new Exception($"{nameof(obj)} 实体多于一个KeyAttribute Propertity");

            return properties.First();
        }

        /// <summary>
        /// 获取属性Key
        /// </summary>
        /// <param name="typeInfo"></param>
        /// <returns></returns>
        public static PropertyInfo GetKeyPropertity(this Type typeInfo)
        {
            var properties = typeInfo.GetProperties().Where(a => a.GetCustomAttribute<Tool.Model.DBFieldInfo>().IsPrimarykey).ToArray();

            if (!properties.Any())
                throw new Exception($"the type {nameof(typeInfo.FullName)}实体没有KeyAttribute Propertity");

            if (properties.Length > 1)
                throw new Exception($"the type {nameof(typeInfo.FullName)} 实体多于一个KeyAttribute Propertity");

            return properties.First();
        }
    }
}
